<?php
/**
 *@author sparkguo 
 *@date 2017-09-22 日本yahoo订单导入
 */
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('max_execution_time', '0');
class JpYahooOrder extends CI_Controller {
    
    var $md5_key='a1bd5c77992550073ae959bd939734c4';
	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
        $this->load->model('Product_m','pm');
		$this->pageSize =$this->config->item('pagenum'); 
        $this->CI =& get_instance();
        
    }
	function ajaxbutton(){
		$op = trim($this->input->get_post('op'));	
        if($op =='getMadeOrderList'){
            $this->getMadeOrderList();
		}
        if($op=='getMadeOrderDetail'){
            $this->getMadeOrderDetail();    
        }
        if($op=='setPurchaseVal'){
            $this->setPurchaseVal();
        }
        if($op=='getFactory'){
            $this->getFactory();
        }
        if($op=='setOnePurchase'){
            $this->setOnePurchase();
        }
        if($op=='setPurchShipment'){
            $this->setPurchShipment();
        }
        if($op=="getTbKdinfo"){
            $this->getTbKdinfo();
        }
        
	}
    
    function getFactory(){
        $factorys=$this->db->get('db_factory')->result_array();
        echo json_encode($factorys);
    }
    
    function getMadeOrderList(){
		$nowpage = $_REQUEST["pageid"];
        $factoryid= $this->input->get_post('factoryid');
        $made_status=$this->input->get_post("made_status");
        $orderstockid=$this->input->get_post("orderstockid");
        if ($nowpage == "") $nowpage = 1;
        $where = "";//and ps=2		
		$orderby = " order by opertime desc";
        if(!empty($made_status)){
            $made_status=$made_status-1;
            $where .= " and made_status=$made_status";
        }
        if(!empty($orderstockid)){
            $orderstockid=trim($orderstockid);
            $where .= " and orderstockid='$orderstockid'";
        }
        if($factoryid>0){
            $where.=" and made_factory in('".$factoryid."')";  
        }else{
            $where.=" and made_factory not in(1,2,3)";
        }
        $list = $this->fun->getalllist("db_purchase_list ", $where, $nowpage, $if_csv, 20, $orderby);
        //echo $this->db->last_query();
        
		foreach($list["list"] as $key=>$rs)
		{
			 $waittime = strtotime($rs['opertime']) + 86400*$rs['daysum'];
			 $list["list"][$key]['waittime'] =date("Y-m-d H:i:s",$waittime);

		}
        echo json_encode($list);    
    }
    
    function getTbKdinfo(){
        $id= $this->input->get_post('id');
        $where = " and id in($id)";		
		$orderby = " order by opertime desc";
        //if($factoryid)$where.=" and made_factory in('".$factoryid."')";
        $list = $this->fun->getalllist("db_purchase_list ", $where, 1, $if_csv, 20, $orderby);
        $newinfolist=array();
		foreach($list["list"] as $key=>$rs)
		{
			 $datas=unserialize($rs['tb_kd']);
             $datas['id']=$rs['id'];
             $datas['orderstockid']=$rs['orderstockid'];
             $newinfolist[]=$datas;
		}
        echo json_encode($newinfolist);    
    }
    
    function getMadeOrderDetail(){
        $id=$this->input->post_get('dataid');
		if($id > 0){
            $this->load->model('Purchase_m','m');
			$detail = $this->m->getBuyListByUid($id);
	        $this->tpl->assign("detail",$detail);
			$detail_list = $this->m->getBuyListvice($detail['id']);
			$this->tpl->assign("detail_list",$detail_list);
            
            $storagelist = $this->db->get_where('db_storage', 'isdel=0')->result_array();
            foreach($storagelist as $key=>$li){
                if($li['id']=$detail['cang']){
                    $detail['storage']=$li['storagename'];
                }
            }
            $outputdata=array('detail'=>$detail,'detail_list'=>$detail_list);
            
            echo json_encode($outputdata);
	     }  
    }
    
    function setPurchaseVal(){
        $changeids=$this->input->get_post('changeids');
        $made_status_time=$this->input->get_post('made_status_time');
        $made_status=$this->input->get_post('made_status');
        $auth_key=$this->input->get_post('auth_key');
        $upids=trim($changeids,',');
        if(md5($changeids.$this->md5_key)==$auth_key){
            $updata=array('made_status_time'=>$made_status_time,'made_status'=>$made_status); 
            $this->db->update('db_purchase_list', $updata, 'id in('.$upids.')');
            $resultdata=array('status'=>1,'msg'=>'修改成功');   
        }else{
            $resultdata=array('status'=>0,'msg'=>'验证代码错误，无权修改');            
        }
        echo json_encode($resultdata);
    }
    
    function setOnePurchase(){
        $changeids=$this->input->get_post('changeids');
        $kdname[]=$kdname_str=$this->input->get_post('kdname');
        $kdnumber[]=$kdnumber_str=$this->input->get_post('kdnumber');
        $tborder[]=$this->input->post('tborder');
        $daysum=$this->input->get_post('daysum');
        $made_status=$this->input->get_post('made_status');
        $auth_key=$this->input->get_post('auth_key');
        $upids=trim($changeids,',');
        
        $daysum_date_limit=strtotime($daysum);
        $applytime_limit=strtotime($_POST['opertime']);	
        $daysum=ceil(($daysum_date_limit-$applytime_limit)/86400);
        if(md5($changeids.$this->md5_key)==$auth_key){
            $newarray["kdname"] = $kdname;
            $newarray["tborder"] = $tborder;
			$newarray["kdnumber"] = $kdnumber;
			$newarr = serialize($newarray);
            $updata=array('daysum'=>$daysum,'tb_kd'=>$newarr,'made_status'=>$made_status);
            
            $purchaseinfo=$this->fun->getdatabasesdetail("db_purchase_list"," and id=".$upids);
            $made_status_arr=array('待生产',"生产中",'生产完成','已发运');
            $p_status=array(1=>'新采购单',2=>'采购完成');
            $msg = "将生产状态由{$made_status_arr[$purchaseinfo[made_status]]}更新为{$made_status_arr[$made_status]} ";
            $kdname=trim($kdname_str);$kdnumber=trim($kdnumber_str);
            if(($kdname!='' and $kdnumber!='') or $made_status==3){
                $updata['status']=2;
                //$updata['made_status']=$updata['made_status']<3?3:$updata['made_status'];
                    $msg = "将生产状态由{$made_status_arr[$purchaseinfo[made_status]]}更新为{$made_status_arr[$updata[made_status]]} ";
                    //$msg =$made_status==3?$msg."快递信息由{$purchaseinfo[tb_kd]}更新为{$newarr}":$msg;
                    $msg .= "<br />将状态由：{$p_status[$purchaseinfo[status]]}更改为：采购完成";    
            }
            
    			$arr_logs['createtime'] = date("Y-m-d H:i:s");
    			$arr_logs['goods_code'] = $purchaseinfo['orderstockid'];
    			$arr_logs['details'] = $msg;
    			$arr_logs['username'] = '供应商:'.$_POST['username'];
    			$arr_logs['userid'] = 108601;
    			$arr_logs['purchase_id'] = $upids;
    			$this->db->insert('db_externalbuy_log', $arr_logs);
                
            $this->db->update('db_purchase_list', $updata, 'id in('.$upids.')');
            $resultdata=array('status'=>1,'msg'=>'修改成功');   
        }else{
            $resultdata=array('status'=>0,'msg'=>'验证代码错误，无权修改');            
        }
        echo json_encode($resultdata);
    }
    
    function setPurchShipment(){
        $changeids=$this->input->get_post('changeids');
        $kdname=$this->input->get_post('kdname');
        $kdnumber=$this->input->get_post('kdnumber');
        $tborder=$this->input->post('tborder');
        $made_status_time=date("Y-m-d H:i:s");
        $made_status=3;
        $auth_key=$this->input->get_post('auth_key');
        $kdname=explode(',',$kdname);	
        $kdnumber=explode(',',$kdnumber);
        $tborder=explode(',',$tborder);
        $list_id=explode(',',$changeids);
        if(md5($changeids.$this->md5_key)==$auth_key){
            for($i=0;$i<count($list_id);$i++){
                $purchaseinfo=$this->fun->getdatabasesdetail("db_purchase_list"," and id=".$list_id[$i]);
                $newarray["kdname"] = array($kdname[$i]);//$newarray["tborder"] = $this->input->post('tborder');
    			$newarray["kdnumber"] = array($kdnumber[$i]);
                $newarray["tborder"] = array($tborder[$i]);
    			$newarr = serialize($newarray);
                $made_status_arr=array('待生产',"生产中",'生产完成','已发运');
                $p_status=array(1=>'新采购单',2=>'采购完成');
                $updata=array('made_status_time'=>$made_status_time,'made_status'=>$made_status,'tb_kd'=>$newarr); 
                $msg = "将生产状态由{$made_status_arr[$purchaseinfo[made_status]]}更新为{$made_status_arr[$made_status]} ";
                if($kdname[$i]!='' and $kdnumber[$i]!=''){
                    $updata['status']=2; 
                    $msg =$made_status==3?$msg."快递名称由{$purchaseinfo[tb_kd]}更新为{$newarr}":$msg;
                    $msg .= "<br />将状态由：{$p_status[$purchaseinfo[status]]}更改为：采购完成";       
                }
    			$arr_logs['createtime'] = date("Y-m-d H:i:s");
    			$arr_logs['goods_code'] = $purchaseinfo['orderstockid'];
    			$arr_logs['details'] = $msg;
    			$arr_logs['username'] = $_POST['username'];
    			$arr_logs['userid'] = 108601;
    			$arr_logs['purchase_id'] = $list_id[$i];
    			$this->db->insert('db_externalbuy_log', $arr_logs);
            
                $this->db->update('db_purchase_list', $updata, 'id ='.$list_id[$i]);
            }
            $resultdata=array('status'=>1,'msg'=>'修改成功');   
        }else{
            $resultdata=array('status'=>0,'msg'=>'验证代码错误，无权修改');            
        }
        echo json_encode($resultdata);
    }
    
    public function checkOrderShipTrack(){
        $shiplasttime=strtotime("-15 day");
        $yahooShiplist=$this->fun->getdatabaseslist("db_mabangorder"," AND orderType=10 and");
		if(count($goodslist)>0){
		 
        }
    }
    //
    public function setYahooOrderShipStatus(){
        //getYIDAgettrack    
    }
    
    /**
     * Call DHL Service
     * @param Request $request Request to send
     * @return string DHL XML response string
     */
    public function call($url,$request){
        if (!$ch = curl_init()){
            throw new \Exception('could not initialize curl');
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_PORT , 443);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$request);
        $result = curl_exec($ch);
        if (curl_error($ch)){
            return false;
        }else{
            curl_close($ch);
        }
        return $result;
    }
    
    
    function saveRequestOrder(){
        $this->load->library('amazondata');
        $this->db148=$this->CI->load->database('amazondata', TRUE);
        $createTimeTo=date("Y-m-d")." ".date("23:i:s");
        $createTimeFrom=date("Y-m-d",strtotime("-4 day"))." 00:00:00";
        
        $order_list=$this->db148->query("select * from db_jp_yahoo_order where CreateTime BETWEEN '$createTimeFrom' and '$createTimeTo'")->result_array();
        echo "开始同步 $createTimeFrom 至 $createTimeTo 保存到148数据库的订单".count($order_list)."条<br />";  
        	foreach($order_list as $k=>$v){
        	   $full_orderid=$v['orderID'];
			     $shopinfo=$this->fun->getdatabasesdetail("d_shop"," and name='JP-Yahoo'");
				$sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['orderID']}' ";
				$rs_order = $this->db->query($sql_order)->row_array();
				if($rs_order){
				    echo "交易号:".$v['orderID']."的订单已经存在，执行跳过<br />";
					continue;
				}
                $country_code=strtoupper(trim("JP"));
                //获取国家名称与信息
				$countryinfo = $this->fun->getdatabasesdetail("d_country"," AND countryid='".$country_code."'");
                $platforminfo=$this->fun->getdatabasesdetail("db_platform"," and name='Yahoo'");
                //汇率
                $exchange=$this->db->get_where("d_moneyrate","name='JPY'")->result_array();
    			$exchangerate=$exchange[0]["rate"];
                $v['orderID']=explode('-',$v['orderID']);
                $v['orderID']=$v['orderID'][1]!=''?$v['orderID'][1]:$v['orderID'][0];
                
				$arr_order_list['order_sn'] = $this->amazondata->getNo('bonanza',$v['orderID'],$shopinfo['id']);//生成订单序号
				$arr_order_list['dates']  = date("Y-m-d"); //当天日期 判断order_sn使用
				$arr_order_list['ordertime']  = $v['OrderTime']; //订单日期时间
				$arr_order_list['order_source']  = "正常订单"; //默认
				$arr_order_list['customerid']  = $v['ShipCustomer']; //客户id
				$arr_order_list['consignee']  =$v['ShipCustomer']; //收货人
				$arr_order_list['country']  = $countryinfo['countrynamecn'];
				$arr_order_list['country_code']  = $countryinfo['country']; //国家
				$arr_order_list['country_cn']  = $countryinfo['countrynameen']; //国家英文
				//$arr_order_list['province']  =;
				$arr_order_list['city']  = $v['ShipProvince']." ".$v['ShipCity'];
				$arr_order_list['address']  = $v['ShipAddress1'].$v['ShipAddress2'];
				//$arr_order_list['address2']  = $v['ShipAddress2'];
				$arr_order_list['zipcode']  = $v['ShipZipCode'];
                
				$arr_order_list['tel']  = $v['ShipPhoneNumber'];
				//$arr_order_list['mobile']  = $v['mobileNo'];
				$arr_order_list['shopid']  = $shopinfo['id']; //店铺id
				$arr_order_list['shopname']  = $shopinfo['name'];
				$arr_order_list['shopoper']  = $shopinfo['updateoper'];//店铺负责人
               	
                
				$arr_order_list['moneytype']  = 'JPY';//货币类型
				$arr_order_list['tradeid']  = $full_orderid; //交易单号
				$arr_order_list['goods_originask']  = $v['TotalPrice']; //订单金额
				$arr_order_list['goods_amount']  = $v['TotalPrice']*$exchangerate;
				//$arr_order_list['shipping_originask']  =$ship_price['amount']; //原始快递费
				//$arr_order_list['shipping_fee']  =$arr_order_list['shipping_originask']*$exchangerate; //物流费 人民币
				
				$arr_order_list['pay_fee']  =$arr_order_list['goods_amount'] * 0.015; //支付费用
                //$arr_order_list['email'] = $transinfo['buyer']['email']; //
				$arr_order_list['platform_fee']  = $arr_order_list['goods_amount']*0.15; //平台费用
				$arr_order_list['add_time'] = time();
				$arr_order_list['saleschannel']  = 'Yahoo';
                $arr_order_list['platformID']  = $platforminfo['id'];//
                $arr_order_list['moneyrate']  = $exchangerate;//当前汇率
                
				$arr_order_list['order_status']  = 2; //已支付
                //$arr_order_list['payid']  = $transinfo['providerID'];

				//留言
				if($v['BuyerComments']){
					$arr_order_list['BuyerComments']  = $v['BuyerComments']; //备注
				}
				$this->db->trans_begin();	//事务开始
				$this->db->insert('db_order_list',$arr_order_list);
                echo'成功导入一条订单'.$arr_order_list['order_sn'].'<br />';
                //echo $this->db->last_query()."<br />";
				$insert_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
				//更新日志记录
				$imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'Yahoo接口更新148订单,交易号='.$v['orderID'];
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);
                $SellInfos=json_decode($v['SellInfoJson'],true);
                //卖出物品信息存入
				$error_flag =0;
                $weighttotal=0;
				foreach($SellInfos as $key=>$SellInfo){
				    $goodsinfo=$SellInfo;
                    $goodsinfo['oldsku']=$goodsinfo['sku'];
                    
					$arr_order_sell['order_id'] = $insert_id;
                    $arr_order_sell['goods_name'] = $v['ItemOption'];
                    if(empty($goodsinfo["sku"])){
					    $arr_order_sell['goods_id'] = 0;
                        $error_flag=1;
                    }else{
                        $parent_goods = $this->fun->getdatabasesdetail("db_goods_parent"," and p_parent_sku='".$goodsinfo['sku']."'");
                        if($parent_goods){
                            $buygoods_size=explode(" ",trim($goodsinfo['variations']['variation'][0]['nameValueList']['value']));
                            $buygoods_size=$buygoods_size[count($buygoods_size)-1];
                            $rgoods = $this->fun->getdatabasesdetail("db_goods",
                            " and goods_parentID='".$parent_goods['p_parent_id']."' and goods_sku like '%-{$buygoods_size}'");
                        }
                        if($rgoods['goods_id']==''){
                            $rgoods = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".$goodsinfo['sku']."'");    
                        }
                        if($rgoods){
                            $goodsinfo['sku']=$rgoods['goods_sku'];
                            $arr_order_sell['goods_name']=$rgoods['goods_name'];
                        }
                        if($rgoods["goods_id"]==null){
                            $error_flag=1;
                        }
                        $rgoods["goods_id"]=$rgoods["goods_id"]==null?0:$rgoods["goods_id"];
                        $arr_order_sell['goods_id']=$rgoods["goods_id"];
                        $arr_order_sell['costprice'] = empty($rgoods['g_costprice'])?'':$rgoods['g_costprice']*$goodsinfo['quantity'];//物品成本价
                        $weight = $goodsinfo['quantity']* $rgoods["g_weight"];
                        $arr_order_sell['goods_weight'] = $weight;//毛重
                        $weighttotal+=$weight;
                    } 
                    $goodsinfo['sku']=empty($goodsinfo['sku'])?'':$goodsinfo['sku'];
                    
                    $sizeinfo='';
                    if(is_array($goodsinfo['variations']['variation'])){
                        foreach($goodsinfo['variations']['variation'] as $sizekey=>$sizeval){
                            $sizeinfo.=" ".$sizeval['nameValueList']['name'].":".$sizeval['nameValueList']['value'];    
                        }
                        $sizeinfo=trim($sizeinfo);
                    }
                    
                    $sizeinfo=$sizeinfo==":"?"":$sizeinfo;
                    $arr_order_sell['goods_sn'] = $goodsinfo['sku'];
                    $arr_order_sell['sale_remark']=$sizeinfo;
					$arr_order_sell['goods_number'] = $goodsinfo['quantity']; //商品数量
					$arr_order_sell['originsellprice'] = $goodsinfo['unit_price'];
                    $arr_order_sell['goods_price'] = $goodsinfo['unit_price']*$exchangerate;
                    $arr_order_sell['originsku'] = $goodsinfo['oldsku'];//原始sku
					$arr_order_sell['goods_amount'] =$goodsinfo['unit_price']*$goodsinfo['quantity']*$exchangerate;
					$this->db->insert('db_order_sell',$arr_order_sell);
                    //echo $this->db->last_query()."<br />";
                    
					$insert_sell_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
		              
				}
                if(count($SellInfos)<1){
                    $error_flag=1;    
                }
				if($error_flag || $arr_order_sell['goods_weight']>0 ){
					$this->db->where('order_id',$insert_id);
                    if($error_flag){
                        $data['order_status'] = 7;    
                    }
					$data['orderweight'] = $weighttotal;
					$this->db->update('db_order_list',$data);
				}
				//若执行成功，则提交
				if ($this->db->trans_status() === FALSE){
					$this->db->trans_rollback();
				}else{
					$this->db->trans_commit();
				}
			};  
            

        echo '同步yahoo订单完成';
    } 
    
    
}
